import React from 'react';
import { formatMessage } from 'umi-plugin-react/locale';
import { Button, Col, Form, Input, message, Modal, Row, Select, Table, Pagination, Upload } from 'antd';
import {
  fakeCommonQuestionList,
  postCommonQuestionAdd,
  postCommonQuestionEdit,
  getCommonQuestionDel,
  postCommonQuestionImport,
  getCommonQuestionExport,
} from '@/services/commonProblem';

class CommonProblem extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      loading: false,
      total: 0,
      current: 1,
      size: 10,
      search: '',
      visible: false,
      id: '',
      uploading: false,
    };
    this.columns = [
      {
        title: formatMessage({ id: 'digitalEmployees.commonProblem.serialNumber' }),
        dataIndex: 'orderId',
        align: 'center',
        width: 150,
      },
      {
        title: formatMessage({ id: 'digitalEmployees.commonProblem.question' }),
        dataIndex: 'question',
        align: 'center',
      },
      {
        title: formatMessage({ id: 'digitalEmployees.commonProblem.action' }),
        align: 'center',
        width: 240,
        render: (text, row, index) => {
          return (
            <span style={{ display: 'flex', alignItems: 'center', gap: '12px', justifyContent: 'center' }}>
              <Button size={'small'} type='primary' icon={'edit'} onClick={() => this.openBottomModal(row)}>
                {formatMessage({ id: 'digitalEmployees.commonProblem.edit' })}
              </Button>
              <Button size={'small'} type='danger' icon={'delete'} onClick={() => this.isDelete(row.id)}>
                {formatMessage({ id: 'digitalEmployees.commonProblem.delete' })}
              </Button>
            </span>
          );
        },
      },
    ];
  }

  componentDidMount() {
    this.getList();
  }

  /* 获取用户类型-筛选框 */
  getList = async () => {
    let { applicationId } = this.props;
    let { current, size, search } = this.state;
    let obj = { current, size, search, applicationId };
    let res = await fakeCommonQuestionList(obj);
    console.log(res);
    this.setState({
      list: res.records,
      total: res.total,
    });
  };

  /* 分页 */
  changePagination = (current, size) => {
    this.setState({ current, size }, () => this.getList());
  };

  /* 条件查询 */
  searchByParams = () => {
    this.setState({ current: 1 }, () => this.getList());
  };

  changeByParams = (e) => {
    this.setState({ search: e.target.value });
  };

  /* 是否删除标签 */
  isDelete = (id) => {
    const that = this;
    Modal.confirm({
      title: formatMessage({ id: 'digitalEmployees.commonProblem.confirmDelete' }),
      okText: formatMessage({ id: 'digitalEmployees.commonProblem.confirm' }),
      okType: 'danger',
      cancelText: formatMessage({ id: 'digitalEmployees.commonProblem.cancel' }),
      onOk() {
        that.deleteQuestion(id);
      },
    });
  };

  /* 删除标签 */
  deleteQuestion = async (id) => {
    const res = await getCommonQuestionDel({ id });
    const { list, current } = this.state;
    if (list.length === 1 && current > 1) {
      this.setState({ current: current - 1 }, () => this.getList());
    } else {
      this.getList();
    }
    message.info(res.msg);
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { list, loading, current, total, search, size, uploading, id } = this.state;
    const { applicationId } = this.props;
    const uploadProps = {
      multiple: false,
      showUploadList: false,
      beforeUpload: () => {
        return false;
      },
      accept: '.xlsx,.xls',
      onChange: this.onFileChange,
    };

    return (
      <div>
        <div style={{ marginBottom: 20, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
              <Input
                placeholder={formatMessage({ id: 'digitalEmployees.commonProblem.searchPlaceholder' })}
                style={{ width: '220px' }}
                value={search}
                onChange={this.changeByParams}
              />
              <Button type={'primary'} onClick={this.searchByParams}>
                {formatMessage({ id: 'digitalEmployees.commonProblem.query' })}
              </Button>
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
              <Button type={'primary'} onClick={() => this.openBottomModal(null)}>
                {formatMessage({ id: 'digitalEmployees.commonProblem.add' })}
              </Button>
              <Upload {...uploadProps}>
                <Button type={'primary'} loading={uploading}>
                  {formatMessage({ id: 'digitalEmployees.commonProblem.import' })}
                </Button>
              </Upload>
              <Button type={'primary'} onClick={this.exportExcel}>
                {formatMessage({ id: 'digitalEmployees.commonProblem.export' })}
              </Button>
            </div>
          </div>
        </div>

        <Table rowKey={'id'} columns={this.columns} dataSource={list} loading={loading} pagination={false} scroll={{ x: 1300, y: 470 }} />
        {total > 10 ? (
          <Pagination
            style={{ textAlign: 'right', marginTop: 16 }}
            total={total}
            current={current}
            onChange={this.changePagination}
            // showSizeChanger={true}
            showQuickJumper={true}
            // onShowSizeChange={this.changePagination}
          />
        ) : null}

        <Modal
          title={
            id && id != ''
              ? formatMessage({ id: 'digitalEmployees.commonProblem.editTitle' })
              : formatMessage({ id: 'digitalEmployees.commonProblem.addTitle' })
          }
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <div style={{ height: '24px', lineHeight: '24px', margin: '-10px 0 10px' }}>
            {formatMessage({ id: 'digitalEmployees.commonProblem.questionLabel' })}
          </div>
          <Input value={this.state.question} onChange={this.changeByQuestion} />
        </Modal>
      </div>
    );
  }

  /* 打开编辑框 */
  openBottomModal = (row) => {
    this.setState({ visible: true, id: row ? row.id : '', question: row ? row.question : '' });
  };

  changeByQuestion = (e) => {
    this.setState({ question: e.target.value });
  };

  handleOk = async () => {
    let { applicationId } = this.props;
    let { id, question } = this.state;
    let res = { code: -1, data: false, message: '操作失败' };
    if (id && id != '') {
      res = await postCommonQuestionEdit({ id, question });
    } else {
      res = await postCommonQuestionAdd({ applicationId, question });
    }
    console.log(res);
    if (res.code == 0) {
      message.success('操作成功');
      this.handleCancel();
      this.getList();
    }
  };

  handleCancel = () => {
    this.setState({ visible: false, question: '' });
  };

  getFileNameType = (fileName) => {
    let type = fileName
      ? fileName.split('.')
        ? fileName.split('.').length > 1
          ? fileName.split('.')[fileName.split('.').length - 1]
          : null
        : null
      : null;
    return type;
  };

  onFileChange = async (info) => {
    if (info.file.size > 30 * 1024 * 1024) {
      message.error(`上传文档不能大于30M!`);
      return;
    } else if (this.getFileNameType(info.file.name).toLowerCase() !== 'xls' && this.getFileNameType(info.file.name).toLowerCase() !== 'xlsx') {
      message.error('仅支持文件格式：.xls .xlsx');
      return;
    } else {
      this.setState({ uploading: true }, () => this.uploadFile(info.file));
    }
  };

  uploadFile = async (file) => {
    let { applicationId } = this.props;
    let formData = new FormData();
    formData.append('file', file);
    formData.append('applicationId', applicationId);

    let res = await postCommonQuestionImport(formData);
    console.log(res);
    if (res.code == 0) {
      message.success('上传成功！');
      this.setState({ uploading: false }, () => this.getList());
    }
  };

  exportExcel = async () => {
    let { applicationId } = this.props;
    let res = await getCommonQuestionExport({ applicationId });
  };
}

export default Form.create()(CommonProblem);
